#!/bin/sh
###############################################################################
##  Author    : xuezhoyi
##  Name      : edw_dcss_report.sh
##  Functions : 
##  Purpose   : 
##  Revisions or Comments
##  VER        DATE        AUTHOR           DESCRIPTION
##---------  ----------  ---------------  ------------------------------------ 
##  1.0      2017-05-22  xuezhouyi        1. CREATED THIS SHELL.
###############################################################################

. ${0%`basename ${0}`}edw_parm.sh
. ${0%`basename ${0}`}edw_func.sh

function USAGE(){
    echo -e "\nHow to use this shell script!"
    echo -e '\n${V_SHELL_HOME}/edw_dcss_report.sh 20170101'
}

# Check variable
if [[ -z ${1} ]];then
    USAGE
    exit 1
fi

# Define basic parm
V_SCRIPT_NAME=$(basename ${0} | cut -d'.' -f1)
V_OUT_LOGS="${V_SHELL_LOGS}/${V_SCRIPT_NAME}_${V_TIME_STAMP}_$$.log"

# Define the output flow
exec 4>&1               # screen output
exec 3>>${V_OUT_LOGS}   # script output
exec 2>&3               # error output
exec 1>&3               # standard output
echo -e "[Begin: $(date +%F) $(date +%T)]"

# Get parm
V_DATA_DATE=${1}
echo -e "\nToday batch date is ${V_DATA_DATE}."

if [[ ${V_DATA_DATE:4:4} == '0101' ]];then
    echo -e "skip!!!"
    echo -e "\n[End: $(date +%F) $(date +%T)]"
    echo 0 >&4
    exit 0
fi

# Run procedure
V_QUERY="SELECT CONCAT(PROC_NAME,'|',JOB_TYPE) FROM ETL.EDW_PROC_CONTROL WHERE IF_VALID = 'Y' ORDER BY JOB_GROUP,SEQ_NO;"
V_PROC_LIST=$(${V_RUN_MYSQL} -q "${V_QUERY}")
for POC in ${V_PROC_LIST};do
    V_PROC_NAME=$(echo ${POC} | awk -F'|' '{print $1}')
    V_JOB_TYPE=$(echo ${POC} | awk -F'|' '{print $2}')
    
    if [[ ${V_JOB_TYPE} == 'RPY' || ${V_JOB_TYPE} == 'IFS' ]];then
        V_QUERY="CALL ${V_PROC_NAME}('${V_DATA_DATE}','','','');"
        echo -e "\nStart to: ${V_QUERY}"
        ${V_RUN_MYSQL} -q "${V_QUERY}"
        echo -e "DONE."
    else
        V_QUERY="CALL ${V_PROC_NAME}('${V_DATA_DATE}',@RC);SELECT @RC;"
        echo -e "\nStart to: ${V_QUERY}"
        V_RC=$(${V_RUN_MYSQL} -q "${V_QUERY}")
        if [[ ${V_RC} -eq 0 ]];then
            echo -e "DONE."
        else
            echo -e "FAIL."
            x=fail
        fi
    fi
done

# Check all
if [[ ${x} == "fail" ]];then
    echo 1 >&4
    exit 1
fi

echo -e "\n[End: $(date +%F) $(date +%T)]"
echo 0 >&4
exit 0
